/*
 * @Author: duchengdong
 * @Date: 2021-12-28 11:33:40
 * @LastEditors: lizhen
 * @LastEditTime: 2021-12-29 14:05:46
 * @Description:
 */
import {API_PATH} from '@/config/config'
const UPLOAD_FILE_URL = API_PATH + '/sys/upload'
const mixinUploadFile = {
	data() {
		return {
			img_isLoading: false, //图片是否在上传中
			img_noOnShow: false, //判断是否触发onShow生命周期，用于解决上传图片时触发onShow的问题
		}
	},
	methods: {
		//上传图片
		async uploadHandle() {
			// 选择图片
			let chooseRes = await this.chooseImage()
			if (chooseRes) {
				// 上传图片
				let uploadRes = await this.uploadFile(chooseRes)
				return uploadRes ?? false
			}
			return false
		},
		async chooseImage(count = 1) {
			let _that = this
			_that.img_noOnShow = true
			let res = await uni.chooseImage({
				count, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'], //从相册选择
			})
			if (res[1]) {
				const filePath = res[1].tempFilePaths[0]
				//loading
				_that.img_isLoading = true
				// 上传图片
				return filePath
			} else {
				_that.img_noOnShow = false
				return false
			}
		},
		async uploadFile(filePath) {
			let _that = this
			let resArr = await uni.uploadFile({
				url: UPLOAD_FILE_URL,
				name: 'file',
				filePath,
			})
			if (resArr[0]) {
				_that.showError(resArr[0].errMsg)
				return false
			} else {
				const res = resArr[1]
				const resData = JSON.parse(res.data)
				if (resData.code == 100) {
					return resData.data.url
				}
				return false
			}
		},
		showError(msg) {
			uni.showToast({
				title: msg,
				duration: 2000,
			})
			//loading
			this.img_isLoading = false
			this.img_noOnShow = false
		},
	},
}
export default mixinUploadFile
